package org.funtester.performance.books.chapter02.section5;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch示例
 */
public class CountDownLatchDemo {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(3);// 创建一个CountDownLatch实例
        for (int i = 0; i < 3; i++) {// 创建3个线程
            new Thread(() -> {// 创建一个线程
                try {
                    Thread.sleep(100);// 睡眠100毫秒
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    countDownLatch.countDown();// 计数器减1
                }
                System.out.println(System.currentTimeMillis() + "  任务完成  " + Thread.currentThread().getName());// 打印日志
            }).start();// 启动线程
        }
        System.out.println(System.currentTimeMillis() + "  等待任务完成  " + Thread.currentThread().getName());// 打印日志
        try {
            countDownLatch.await();// 等待计数器归零
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(System.currentTimeMillis() + "  等待结束  " + Thread.currentThread().getName());// 打印日志

    }

}
